package com.algo.rpc.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * RPC传输解码器
 */
public class RpcDecoderHandler extends MessageToMessageDecoder {

    private static final Logger logger = Logger.getLogger(RpcDecoderHandler.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {

        logger.info("recevied rpc request, msg is " + msg);

        ByteBuf buffer = (ByteBuf) msg;
        if (buffer.readableBytes() < Constants.MESSAGE_HEADER_LENGTH) {
            return;
        }
        // 标记起始位置
        buffer.markReaderIndex();

        // 先读取前四个字节代表报文长度，接着读取报文内容
        int messageSize = buffer.readInt();
        // 如果报文长度不够，说明出现了拆包的情况，这边先不处理，将标记的位置复位
        if (buffer.readableBytes() < messageSize) {
            buffer.resetReaderIndex();
            return;
        }

        byte [] messageBytes = new byte[messageSize];
        buffer.readBytes(messageBytes);

        // 反序列化
        Object object = HessionSerializeUtil.deserialize(messageBytes);

        out.add(object);
    }

}
